package lanbo.cj.lmp.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import lanbo.cj.lmp.BaseApplication;
import lanbo.cj.lmp.bean.Asset;
import lanbo.cj.lmp.bean.DataLocal;

import java.util.ArrayList;
import java.util.UUID;

/**
 * Created by white on 15-10-24.
 */
public class NetChangeBroad extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NetworkInfo.State wifiState = null;
        NetworkInfo.State mobileState = null;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        if (wifiState != null && mobileState != null
                && NetworkInfo.State.CONNECTED != wifiState
                && NetworkInfo.State.CONNECTED == mobileState) {
            updateLocateData();
            // 手机网络连接成功
        } else if (wifiState != null && mobileState != null
                && NetworkInfo.State.CONNECTED != wifiState
                && NetworkInfo.State.CONNECTED != mobileState) {
            Toast.makeText(context, "手机网络连接失败", Toast.LENGTH_LONG).show();
            // 手机没有任何的网络
        } else if (wifiState != null && NetworkInfo.State.CONNECTED == wifiState) {
            updateLocateData();
            // 无线网络连接成功
        }


    }

    private void updateLocateData() {
        LocalData localData = new LocalData();
       // 当有缓存数据时候，同步数据
        final ArrayList datas = localData.getLocalData();
        if (datas != null && datas.size()>0 ){
            for (final Object data :datas){
                BmobObject bmobObject = (BmobObject)data;
                Log.e("本地缓存数据:",data.toString());
                bmobObject.save(BaseApplication.getInstance(), new SaveListener() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(BaseApplication.getInstance(), "本地数据上次成功,记录还剩："+datas.size(), Toast.LENGTH_SHORT).show();
                        datas.remove(data);//只有上传成功了，再将该数据从队列中删掉
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        Log.i("本地数据上传失败", s + data.toString());
                        Toast.makeText(BaseApplication.getInstance(), "本地数据上传失败", Toast.LENGTH_LONG).show();
                    }
                });
            }
            DataLocal dataLocal = new DataLocal();
            dataLocal.setDataList(datas);
            localData.saveLocal(dataLocal);//将数据结果存至本地
        }
    }
}
